<?php
/**
 * ClassName:渠道详情处理器
 * @auditor:leijunxiang
 * @time 2025/4/2 17:30
 */

namespace app\tool\freightForward;

use app\factory\Factory;
use app\model\freightForward\ChannelDetail;
use app\model\freightForward\WarehousePrice;
use app\modelOperate\freightForward\ChannelDetailOpe;
use app\modelOperate\freightForward\ChannelOpe;
use app\modelOperate\freightForward\FreightForwardOpe;
use app\modelOperate\freightForward\WarehousePriceHistoryOpe;
use app\modelOperate\freightForward\WarehousePriceOpe;
use app\tool\ToolBase;
use think\facade\Db;
use think\facade\Log;
use think\model\Collection;

class ChannelDetailHandle extends ToolBase
{
    /**
     * 新增详情(区域名称,公斤数,价格,所属渠道id)
     */
    public function addDetail($areaName, $kg, $price, $channelId)
    {
        Db::startTrans();
        try {
            $this->init();
            //(true/false)渠道id校验(渠道id)
            $flag = $this->channelIdVerify($channelId);
            if (!$flag) {
                $this->errCode = FAIL;
                $this->errMsg = "未找到渠道，无法添加!";
                return false;
            }
            $operate = app(ChannelDetailOpe::class);
            //根据区域名称查询id
            $detailId = $operate->selectIdByAreaName($areaName, $channelId);
            if ($detailId) {
                $this->errMsg = "仓库名称重复，请修改后重试!";
                $this->errCode = FAIL;
                return false;
            }
            //创建时间
            $time = time();
            $obj = ChannelDetail::getObj();
            //渠道id
            $obj->setChannelId($channelId);
            //区域名称
            $obj->setAreaName($areaName);
            //时间
            $obj->setTime($time);
            $flag = $operate->saveData($obj->getAttribute());
            if (!$flag) {
                $this->errMsg = "新增失败，请重试!";
                $this->errCode = FAIL;
                return false;
            }
            //保存仓库价格（重量数组,价格数组,详情id）
            $this->saveWarehousePrice($kg, $price, $obj->getDetailId(),$time);
            //保存仓库历史价格(详情id,仓库价格数组,重量数组)
            $this->saveHistoryPrice($kg, $price, $obj->getDetailId(),$time);
            if (!$this->isGoOn()) {
                Db::rollback();

            } else {
                Db::commit();
            }
        } catch (\Exception $e) {
            $this->errCode = FAIL;
            $this->errMsg = $e->getMessage();
            Db::rollback();
        }
        return $this->isGoOn();
    }

    /**
     * 查询详情(渠道id,页数，条数,区域名称)
     */
    public function selectDetail($channelId, $page, $limit, $areaName)
    {
        $this->init();
        $ope = app(ChannelDetailOpe::class);
        if($areaName){
            //根据id和区域名称查询数据
            $data = $ope->selectDataByChannelIdAndAreaName($channelId, $areaName, $page, $limit);
        }else{
            $data = $ope->selectDataByChannelId($channelId, $page, $limit);
        }
        //查询仓库价格(详情数组)
        $data = $this->selectWarehousePrice($data);
        //详情结果处理(详情数据)
//        $data = $this->detailResult($data);
        $data['totalCount'] = $this->getCount($channelId, $page,$areaName);
        if (empty($data)) {
            $this->errCode = FAIL;
            $this->errMsg = "未查询到数据！";
        }
        return $data;
    }

    /**
     * 查询重量(渠道id)
     */
    public function selectWeight($channelId)
    {
        $this->init();
        $ope = app(ChannelDetailOpe::class);
        $priceOpe = app(WarehousePriceOpe::class);
        //拿到详情id
//        $detailId = $ope->selectDataByChannelId($channelId,1,1)[0]['detailId'];
        $channelData = $ope->selectDataByChannelId($channelId, 1, 1);
        if (empty($channelData)) {
            $this->errMsg = "未找到仓库,请重试!";
            $this->errCode = FAIL;
            return "";
        }
        //根据详情id查询数据
        $arr = $priceOpe->selectDataByDetailId($channelData[0]['detailId']);
        if (empty($arr)) {
            $this->errCode = FAIL;
            $this->errMsg = "未查询到重量";
            return "";
        }
        //重量转换器(仓库价格数组)
        $weight = $this->weightTrans($arr);
        return $weight;
    }

    /**
     * 修改渠道详情(数据)
     */
    public function updateChannelDetail($data)
    {
        Db::startTrans();
        try {
            $this->init();
            //修改仓库数据(仓库数据)
            $this->updateWarehouseData($data);
            //修改详情数据
            $this->updateDetailData($data);
            //保存历史数据
            $this->saveHistory($data);
            if (!$this->isGoOn()) {
                Db::rollback();

            } else {
                Db::commit();
            }
        } catch (\Exception $e) {
            $this->errCode = FAIL;
            $this->errMsg = $e->getMessage();
            Db::rollback();
        }
        return $this->isGoOn();
    }

    /**
     * 删除渠道详情(详情id数组)
     */
    public function delChannelDetail($arr)
    {
        try {
            $this->init();
            $ope = app(ChannelDetailOpe::class);
            if ($arr) {
                foreach ($arr as $item) {
                    $flag = $ope->deleteDetailData($item);
                    if (!$flag) {
                        $this->errCode = FAIL;
                        $this->errMsg = "删除失败，请重试!";
                        break;
                    }
                }
            }

        } catch (\Exception $e) {
            $this->errCode = FAIL;
            $this->errMsg = $e->getMessage();
        }
        return $this->isGoOn();
    }


    /**
     * (true/false)渠道id校验(渠道id)
     */
    protected function channelIdVerify($channelId)
    {
        $data = ChannelOpe::find($channelId);
        if (empty($data)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * (总数)获取总数(渠道id,页数)
     */
    protected function getCount($channelId, $page,$areaName)
    {
        if ($page > 1) {
            return 0;
        }
        $ope = app(ChannelDetailOpe::class);
        if($areaName){
            //根据渠道id和名称查询数量
            $count = $ope->selectCountBayName($channelId, $areaName);
        }else{
            //根据渠道id查询数量
            $count = $ope->selectCount($channelId);
        }

        return $count;
    }

    /**
     * (数据)查询仓库价格(详情id)
     */
    protected function selectWarehousePrice($data)
    {
        if (empty($data)) {
            return [];
        }
        $ope = app(WarehousePriceOpe::class);
        for ($i = 0; $i < count($data); $i++) {
            $detailId = $data[$i]['detailId'];
            $detailData = $ope->selectDataByDetailId($detailId);
            $data[$i]['details'] = $detailData;
            if (empty($detailData)) {
                $this->errCode = FAIL;
                $this->errMsg = "未查询到数据！";
                return [];
            }
        }
        return $data;
    }


    /**
     * 保存仓库价格（重量数组,价格数组,详情id）
     */
    protected function saveWarehousePrice($kgArr, $priceArr, $detailId,$time)
    {
        if (!$this->isGoOn()) {
            return false;
        }
        $kgArr = explode(",", $kgArr);
        $priceArr = explode(",", $priceArr);
        if (count($kgArr) != count($priceArr)) {
            $this->errCode = FAIL;
            $this->errMsg = "保存失败,重量和价格必须一一对应";
            return false;
        }
        $obj = app(WarehousePrice::class);
        $ope = app(WarehousePriceOpe::class);
        for ($i = 0; $i <= count($kgArr) - 1; $i++) {
            //仓库id
            $warehouseId = Factory::createUniqueNumber();
            $obj->setWarehouseId($warehouseId);
            //详情id
            $obj->setDetailId($detailId);
            //重量
            $weight = preg_replace('/[^0-9]/', '', $kgArr[$i]);
            $weight = trim($weight); // 去除前后空格
            $obj->setWeight($weight);

            //重量表名
            $weightName = $kgArr[$i];
            $obj->setWeightName($weightName);
            //time
            $obj->setTime($time);
            //价格
            $price = $priceArr[$i];
            $obj->setPrice($price);
            $flag = $ope->saveData($obj->getAttribute());
            if (!$flag) {
                $this->errMsg = "保存失败，请重试!";
                $this->errCode = FAIL;
                return false;
            }
        }
        return true;
    }

    /**
     * 保存仓库历史价格（重量数组,价格数组,详情id）
     */
    protected function saveHistoryPrice($kgArr, $priceArr, $detailId,$time)
    {
        if (!$this->isGoOn()) {
            return false;
        }
        $kgArr = explode(",", $kgArr);
        $priceArr = explode(",", $priceArr);
        if (count($kgArr) != count($priceArr)) {
            $this->errCode = FAIL;
            $this->errMsg = "保存失败,重量和价格必须一一对应";
            return false;
        }
        $ope = app(WarehousePriceHistoryOpe::class);
        for ($i = 0; $i <= count($kgArr) - 1; $i++) {
            $weight = preg_replace('/[^0-9]/', '', $kgArr[$i]);
            $historyId = Factory::createUniqueNumber();
            $arr = [
                "historyId" => $historyId,
                "detailId" => $detailId,
                "weight" => $weight,
                "price" => $priceArr[$i],
                "weightName" => $kgArr[$i],
                "time" => $time
            ];
            $ope->saveData($arr);
        }
    }

    /**
     * 详情结果处理(详情数据)
     */
    protected function detailResult($result)
    {
        // 组织结果
        $channelData = null;
        $details = [];

        foreach ($result as $row) {
            if ($channelData === null) {
                $channelData = [
                    'detailId' => $row['detailId'],
                    'channelId' => $row['channelId'],
                    'areaName' => $row['areaName'],
                    'details' => []
                ];
            }
            $details[] = [
                'warehouseId' => $row['warehouseId'],
                'weight' => $row['weight'],
                'price' => $row['price']
            ];
        }

        if ($channelData !== null) {
            $channelData['details'] = $details;
        }
        return $channelData;
    }

    /**
     * 重量转换器(仓库价格数组)
     */
    protected function weightTrans($arr)
    {

        $str = "";
        for ($i = 0; $i < count($arr); $i++) {
            if ($i == 0) {
                $str = $arr[$i]['weightName'];
            } else {
                $str .= ("," . $arr[$i]['weightName']);
            }
        }
        return $str;
    }

    /**
     * 修改仓库数据(仓库数据)
     */
    protected function updateWarehouseData($data)
    {
        if (!$this->isGoOn()) {
            return;
        }
        try {
            $ope = app(WarehousePriceOpe::class);
            foreach ($data['warehousePrice'] as $item) {
                //修改
                $flag = $ope->updatePriceData($item);
            }
        } catch (\Exception $e) {
            $this->errCode = FAIL;
            $this->errMsg = $e->getMessage();
        }
    }

    /**
     * 修改详情数据
     */
    protected function updateDetailData($data)
    {
        if (!$this->isGoOn()) {
            return;
        }
        try {
            $ope = app(ChannelDetailOpe::class);
            //获取名称，确认是否相同
            $detailId = $ope->selectIdByAreaName($data['areaName'], $data['channelId']);
            if ($detailId != $data['detailId']) {
                $this->errMsg = "修改失败，同一渠道只允许一个区域名称";
                $this->errCode = FAIL;
                return;
            }
            $flag = $ope->updateDetailData($data);
        } catch (\Exception $e) {
            $this->errCode = FAIL;
            $this->errMsg = $e->getMessage();
        }
    }

    /**
     * 保存历史数据
     */
    protected function saveHistory($data)
    {
        if (!$this->isGoOn()) {
            return;
        }
        $ope = app(WarehousePriceHistoryOpe::class);
        foreach ($data['warehousePrice'] as $item) {
            $historyId = Factory::createUniqueNumber();
            $arr = [
                "historyId" => $historyId,
                "detailId" => $data['detailId'],
                "weight" => $item['weight'],
                "price" => $item['price'],
                "weightName" => $item['weightName'],
                "time" => time()
            ];
            $ope->saveData($arr);
        }

        return $data;

    }


}